const router = require('koa-router')();
const { exec } = require('../mysql/index')

// 接口---/api/
// restful Api
// 1. 一个url  多种请求方式；
// 登陆
router.post('/api/login', async(ctx, next) => {
  const { username, password } = ctx.request.body;
  // exec 数据查询操作/i/o ---> 异步操作
  // 前面写 = 叫同步赋值
  const data = await exec(`select * from users where username='${username}' and password='${password}'`)
  if (data.length) {
    ctx.body = {
      code: 0,
      msg: 'success',
      data
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '用户未找到'
    }
  }
})
// 注册接口
router.post('/api/register', async (ctx, next) => {
  const { username, password, nickname } = ctx.request.body;
  // exec 数据查询操作/i/o ---> 异步操作
  // 前面写 = 叫同步赋值
  const data = await exec(`insert into users (username, password, nickname) values ('${username}', '${password}', '${nickname}')`)
  if (data.affectedRows) {
    ctx.body = {
      code: 0,
      msg: 'success',
      data: {
        insertId: data.insertId
      }
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '注册失败'
    }
  }
})

// 增

// 删除
router.delete('/api/user/:id', async (ctx, next) => {
  const { id } = ctx.params;
  const data = await exec(`delete from users where id=${id}`)
  if (data.affectedRows) {
    ctx.body = {
      code: 0,
      msg: 'success',
      data
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '删除失败'
    }
  }
})

// 改 put patch
router.put('/api/user/:id', async (ctx, next) => {
 // username passworld nickname
 const { username, password, nickname } = ctx.request.body;
 const { id } = ctx.params;
 const data = await exec(`update users set username='${username}' , password='${password}' , nickname="${nickname}" where id=${id}`)
 if (data.affectedRows) {
  ctx.body = {
    code: 0,
    msg: 'success',
    data
  }
} else {
  ctx.body = {
    code: -1,
    msg: '添加失败'
  }
}
})

// 分页 查
router.get('/api/user', async (ctx, next) => {
  const { page, size } = ctx.query;
  const data = await exec(`select * from users order by id asc limit ${size} offset ${page * size}`);
  if (data.length) {
    ctx.body = {
      code: 0,
      msg: 'success',
      data
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '用户未找到'
    }
  }
})



module.exports = router;
